<?php

namespace app\services;

use app\models\Goods;
use app\models\GoodsModels;

class GoodsService extends ServiceBase
{
    /**
     * @param array $params
     * @param int $page
     * @param int $pagesize
     * @return \think\Paginator
     * @throws \think\db\exception\DbException
     */
    public function getLists($params=[], $page=1, $pagesize=10)
    {
        return Goods::lists($params, $page, $pagesize);
    }

    public function getDetail($id)
    {
        $goods = Goods::find($id);

        if ($goods instanceof Goods) {
            return $goods;
        }

        throw new \Exception('商品不存在');
    }

    /**
     * @Description 名录添加
     * @param  [type] $post
     *
     * @return void
     */
    public function add($params)
    {
        try {
            $goods = new Goods();

            foreach ($params as $key => $val) {
                $goods->$key = $val;
            }
            $goods->models = implode(',', $goods->models);
            $goods->save();

            return true;
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage(), 500);
        }
    }

    /**
     * 更新商品
     * @param Goods $goods
     * @param $params
     */
    public function update(Goods $goods, $params)
    {
        foreach ($params as $key => $val) {
            $goods->$key = $val;
        }
        $goods->models = implode(',', $goods->models);
        $goods->save();
    }

    /**
     * 上架商品
     * @param Goods $goods
     */
    public function enable(Goods $goods)
    {
        $goods->status = 1;
        $goods->save();
    }

    /**
     * 下架商品
     * @param Goods $goods
     */
    public function disable(Goods $goods)
    {
        $goods->status = 0;
        $goods->save();
    }

    public function addStock(Goods $goods, $num)
    {
        try {
            $goods->stock += $num;
            $goods->viewCount -= 1;
            $goods->saleCount -= 1;
            $goods->save();
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage(), 500);
        }
    }

    public function reduceStock(Goods $goods, $num)
    {
        try {
            if ($goods->stock < $num) {
                throw new \Exception('库存不足');
            }

            $goods->stock -= $num;
            $goods->viewCount += 1;
            $goods->saleCount += 1;
            $goods->save();

        } catch (\Exception $e) {
            throw new \Exception($e->getMessage(), 500);
        }
    }

    public function getModels()
    {
        $models = GoodsModels::select();

        return $models;
    }
}